/**
 * Main JavaScript file for the Sync Platform
 */
$(document).ready(function() {
    // Set active navigation link based on current URL
    const currentPath = window.location.pathname;
    $('.nav-link').each(function() {
        const href = $(this).attr('href');
        if (href === currentPath || 
            (href !== '/' && currentPath.startsWith(href))) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
    
    // Enable tooltips
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Test connection button handler
    $('.test-connection-btn').on('click', function(e) {
        e.preventDefault();
        const form = $(this).closest('form');
        const url = form.attr('action') + '/test';
        
        $.ajax({
            url: url,
            type: 'POST',
            data: form.serialize(),
            beforeSend: function() {
                $('#connectionTestResult').html('<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>');
            },
            success: function(response) {
                if (response.success) {
                    $('#connectionTestResult').html('<div class="alert alert-success">连接成功!</div>');
                } else {
                    $('#connectionTestResult').html('<div class="alert alert-danger">连接失败: ' + response.message + '</div>');
                }
            },
            error: function() {
                $('#connectionTestResult').html('<div class="alert alert-danger">请求失败，请稍后再试。</div>');
            }
        });
    });
    
    // Toggle task status handler
    $('.toggle-status-btn').on('click', function(e) {
        e.preventDefault();
        const taskId = $(this).data('task-id');
        const currentStatus = $(this).data('current-status');
        const newStatus = currentStatus === 1 ? 0 : 1;
        const btn = $(this);
        
        $.ajax({
            url: '/sync/task/' + taskId + '/status',
            type: 'PUT',
            data: { status: newStatus },
            success: function(response) {
                if (response.success) {
                    btn.data('current-status', newStatus);
                    if (newStatus === 1) {
                        btn.removeClass('btn-success').addClass('btn-danger');
                        btn.html('<i class="bi bi-stop-circle"></i> 停用');
                    } else {
                        btn.removeClass('btn-danger').addClass('btn-success');
                        btn.html('<i class="bi bi-play-circle"></i> 启用');
                    }
                } else {
                    alert('操作失败: ' + response.message);
                }
            },
            error: function() {
                alert('请求失败，请稍后再试。');
            }
        });
    });
    
    // Execute task immediately handler
    $('.execute-task-btn').on('click', function(e) {
        e.preventDefault();
        const taskId = $(this).data('task-id');
        
        if (confirm('确定要立即执行此任务吗？')) {
            $.ajax({
                url: '/sync/task/' + taskId + '/execute',
                type: 'POST',
                success: function(response) {
                    if (response.success) {
                        alert('任务已开始执行，请查看任务日志获取进度信息。');
                    } else {
                        alert('执行失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后再试。');
                }
            });
        }
    });
    
    // Database sync form: Load tables when database selected
    $('#sourceDatabase, #targetDatabase').on('change', function() {
        const dbId = $(this).val();
        const targetElement = $(this).attr('id') === 'sourceDatabase' ? '#sourceTables' : '#targetTables';
        
        if (dbId) {
            $.ajax({
                url: '/database/' + dbId + '/tables',
                type: 'GET',
                success: function(response) {
                    const select = $(targetElement);
                    select.empty();
                    
                    $.each(response, function(i, table) {
                        select.append($('<option></option>').val(table).text(table));
                    });
                    
                    select.prop('disabled', false);
                }
            });
        } else {
            $(targetElement).empty().prop('disabled', true);
        }
    });
}); 